package com.gitee.mrj.aiboot.core.sf.generators.ui.widget;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KV;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.widget.SFSelectWidget;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFSelectWidgetGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFSelectWidget widget = AnnotatedElementUtils.findMergedAnnotation(field, SFSelectWidget.class);
        generate(node, widget);
    }

    private void generate(UIForm node, SFSelectWidget widget) {
        ObjectNode ui = node.getUi();
        ui.put("widget", "select");
        putString(ui, "placeholder", widget.placeholder());
        ui.put("autoClearSearchValue", widget.autoClearSearchValue());
        ui.put("allowClear", widget.allowClear());
        ui.put("borderless", widget.borderless());
        ui.put("autoFocus", widget.autoFocus());
        putString(ui, "dropdownClassName", widget.dropdownClassName());
        ui.put("dropdownMatchSelectWidth", widget.dropdownMatchSelectWidth());
        if (ArrayUtils.isNotEmpty(widget.dropdownStyle())) {
            ObjectNode obj = putObject(ui, "dropdownStyle");
            for (KV kv : widget.dropdownStyle()) {
                obj.put(kv.key(), kv.value());
            }
        }
        ui.put("serverSearch", widget.serverSearch());
        putInt(ui, "maxMultipleCount", widget.maxMultipleCount());
        ui.put("mode", widget.mode().value());
        putString(ui, "notFoundContent", widget.notFoundContent());
        ui.put("showSearch", widget.showSearch());
        putInt(ui, "searchDebounceTime", widget.searchDebounceTime());
        putString(ui, "searchLoadingText", widget.searchLoadingText());
        if (ArrayUtils.isNotEmpty(widget.tokenSeparators())) {
            ArrayNode obj = putArray(ui, "tokenSeparators");
            for (String str : widget.tokenSeparators()) {
                obj.add(str);
            }
        }
        ui.put("showArrow", BooleanUtils.toBoolean(widget.showArrow()));
        putInt(ui, "maxTagCount", widget.maxTagCount());
        putString(ui, "suffixIcon", widget.suffixIcon());
        putInt(ui, "optionHeightPx", widget.optionHeightPx());
        putInt(ui, "optionOverflowSize", widget.optionOverflowSize());
    }


    @Override
    public Class[] supports() {
        return new Class[]{SFSelectWidget.class};
    }
}
